package parser;

import org.w3c.dom.*;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

/**
 * @author 石小俊
 */
public class PrintDOM {

    public static void main(String[] args) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(PrintDOM.class.getClassLoader().getResourceAsStream("students.xml"));
            // 获取根标签
            Element root = document.getDocumentElement();
            print(root);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 递归操作,解析xml文件
     * @param root
     */
    public static void print(Element root) {
        // 打印开始标签 begin
        System.out.print("<" + root.getTagName());

        // 打印属性
        NamedNodeMap attributes = root.getAttributes();
        for(int i = 0; i < attributes.getLength(); i++){
            System.out.print(" "+attributes.item(i));
        }

        // 打印开始标签 end
        System.out.print(">");

        // 打印标签体内容
        NodeList nodes = root.getChildNodes();
        for(int i = 0; i < nodes.getLength(); i++){
            Node node = nodes.item(i);

            // 判断节点类型
            if(node.getNodeType() == Node.TEXT_NODE){
                // 如果是文本节点,则直接打印文本内容
                System.out.print(node.getTextContent());
            }
            if(node.getNodeType() == Node.ELEMENT_NODE){
                // 如果是元素节点,递归操作
                Element ele = (Element) node;
                print(ele);
            }
        }

        // 打印结束标签
        System.out.print("</"+root.getTagName()+">");
    }

}
